package com.project.config;

import com.alibaba.fastjson.JSONObject;
import com.project.util.SysToken;
import com.project.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class MyRealm extends AuthorizingRealm {

    /**
     * 授权  把权限交给shiro
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        UserVo user = (UserVo) subject.getPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        JSONObject jsonObject=    JSONObject.parseObject(user.getToken());
        //获得用户拥有的权限
        List<JSONObject> powerList= (List) jsonObject.get("powerList");
        for(JSONObject object:powerList){
            String power= (String) object.get("name");
            //添加用户拥有的权限
            info.addStringPermission(power);
        }
        return info;
    }

    /**
     * 认证  用户交给shiro
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //shiro提供的对象，用来传输数据
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        char[] passArray= token.getPassword();
        String tokenStr=   token.getUsername();
        String json=  SysToken.verifierJwt(tokenStr);//JWT进行token认证
        UserVo userVo=new UserVo();
        userVo.setToken(json);
        if(!json.equals("error")){
            return new SimpleAuthenticationInfo(userVo,passArray,json);
        }

        return null;
    }
}
